package Test;

import Model.User;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JdbcTemplateDemo2 {
    //1. 获取JDBCTemplate对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDatasource());

    /**
     * 1. 添加一条记录
     */
    @Test
    public void test2() {
        String sql = "insert into user(id,name,password,nickname) values(?,?,?,?)";
        int count = template.update(sql, 6,"裴佳乐","123456","仰止");
        System.out.println(count);

    }

    @Test
    public void test3() {
        String sql = "delete from user where id = ?";
        int count = template.update(sql, 6);
        System.out.println(count);
    }


    /**
     * 4.查询id为1001的记录，将其封装为Map集合
     * 注意：这个方法查询的结果集长度只能是1
     */
    @Test
    public void test4() {
        String sql = "select * from user where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 5);
        System.out.println(map);

    }


    /**
     * 5. 查询所有记录，将其封装为List
     */
    @Test
    public void test5() {
        String sql = "select * from user";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }

    /**
     * 6. 查询所有记录，将其封装为Emp对象的List集合
     */
    @Test
    public void test6() {
        String sql = "select * from user";
        List<User> list = template.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int i) throws SQLException, SQLException {
                User user = new User();
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String password=rs.getString("password");
                String nickname =rs.getString("nickname");

                user.setId(id);
                user.setName(name);
                user.setPassword(password);
                user.setNickname(nickname);

                return user;
            }
        });


        for (User user : list) {
            System.out.println(user);
        }
    }

    //    一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
    @Test
    public void test6_2() {

        String sql = "select * from user";
        List<User> list = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        for (User user : list) {
            System.out.println(user);
        }
    }
}

